package com.eascs.spider.yuqing.common.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * zookeeper操作工具类
 * @author hzp
 *
 */
public class ZKUtil {
	
	private static Logger logger = LoggerFactory.getLogger(ZKUtil.class);

	private static final int SESSION_TIMEOUT = 3 * 1000;

	private static ZooKeeper zk = getInstance();
	
	//工作节点注册根路径
	private static final String root = "/workercluser";

	private static synchronized ZooKeeper getInstance(){
		try {
			return zk == null?zk=new ZooKeeper(PropertiesUtil.getConfig("zk"), ZKUtil.SESSION_TIMEOUT, new Watcher() {
				
				@Override
				public void process(WatchedEvent arg0) {
					
				}
			}):zk;
		} catch (IOException e) {
			logger.error("zk初始化异常" ,e);
		}
		return null;
	}
	
	/**
	 * 在根节点注册工作节点地址信息
	 * 根节点创建模式：PERSISTENT
	 * node节点创建模式：EPHEMERAL，临时节点，客户端断线或关闭即消失
	 * @param path
	 * @param ip
	 * @param port
	 * @throws Exception
	 */
	public synchronized static void register(String path ,String ip , String port) throws Exception{
		 // 先创建出父节点  
        if (zk.exists(root, false) == null) 
            zk.create(root, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);  
        // 连接zk创建znode ,工作节点使用临时模式,节点名称顺序递增
        zk.create(root + path, (ip + ":" + port).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);  
	}
	
	/**
	 * 获取工作节点ip，端口信息
	 * @return java.util.list<String>
	 * @throws Exception
	 */
	public synchronized static List<String> getRegisterInfo() throws Exception{
		List<String> childrenNodes = zk.getChildren(root, null);
		List<String> workerList = new ArrayList<String>();
		for(String msg : childrenNodes){
			workerList.add(new String(zk.getData(root+"/"+msg, null, null)));
		}
		return workerList;
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(getRegisterInfo().toString());
	}
}
